package org.micode.common.helper;

import lombok.extern.slf4j.Slf4j;
import org.micode.common.exception.VerifyFailException;
import org.micode.common.utils.AES128Utils;
import org.micode.common.utils.Base64Utils;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

@Slf4j
@Component
public class PasswordHelper {

    public static String decryptAES(byte[] encryptedData, String aesKey, String ivVal) {
        try {
            byte[] result = AES128Utils.decrypt(encryptedData, aesKey, ivVal);
            return byteToStr(result);
        } catch (Exception e) {
            log.error("Password decryption failed!", e);
            throw new VerifyFailException("Abnormal password");
        }
    }

    private static String byteToStr(byte[] buffer) {
        try {
            int length = 0;
            for (int i = 0; i < buffer.length; ++i) {
                if (buffer[i] == 0) {
                    length = i;
                    break;
                }
            }
            return new String(buffer, 0, length, StandardCharsets.UTF_8);
        } catch (Exception e) {
            return "";
        }
    }

    public static String decryptBase64AES(String encryptedBase64Data, String aesKey, String ivVal) {
        return decryptAES(Base64Utils.decodeByte(encryptedBase64Data), aesKey, ivVal);
    }

    public static void main(String[] args) {
        String password = "vcGus43AzYn4ATRkTp6/Hg==";
        String pwd = Base64Utils.decode(password);
        log.info(pwd);
        log.info(decryptBase64AES(password, "n1nLsxcFv4nHakPJ", "n1nLsxcFv4nHakPJ"));
    }

}
